// pages/add-device/add-device.js
const app = getApp()

Page({
  data: {
    currentStep: 1,
    searchKeyword: '',
    currentCategory: 'all',
    selectedDeviceType: '',
    selectedDeviceTypeObj: null,
    selectedRoomIndex: -1,
    selectedRoom: null,
    
    // 设备配置
    deviceConfig: {
      name: '',
      position: '',
      model: '',
      serialNumber: '',
      icon: '/images/devices/light.png'
    },
    
    // 连接状态
    connectionStep: 1,
    isScanning: false,
    isConnecting: false,
    selectedWifi: null,
    wifiPassword: '',
    showManualInput: false,
    manualDeviceId: '',
    
    // 加载状态
    isLoading: false,
    loadingText: '',
    
    // 数据
    roomList: [],
    deviceTypes: [],
    availableIcons: [
      '/images/devices/light.png',
      '/images/devices/light-smart.png',
      '/images/devices/ac.png',
      '/images/devices/tv.png',
      '/images/devices/camera.png',
      '/images/devices/sensor.png',
      '/images/devices/socket.png',
      '/images/devices/curtain.png'
    ],
    availableWifi: []
  },

  onLoad(options) {
    // 获取传递的房间ID
    this.roomId = options.roomId || ''
    this.initData()
    this.loadRoomList()
  },

  // 初始化数据
  initData() {
    const deviceTypes = [
      {
        id: 'smart-light',
        name: '智能灯泡',
        description: '可调节亮度和色温的智能灯泡',
        icon: '/images/devices/light-smart.png',
        category: 'lighting',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '关闭再打开电源开关3次，等待指示灯闪烁'
      },
      {
        id: 'smart-plug',
        name: '智能插座',
        description: '远程控制电器开关的智能插座',
        icon: '/images/devices/socket.png',
        category: 'appliance',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '长按电源按钮5秒，直到指示灯快闪'
      },
      {
        id: 'ac',
        name: '智能空调',
        description: '支持远程控制和温度调节的空调',
        icon: '/images/devices/ac.png',
        category: 'climate',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '同时按住温度和模式键5秒进入配对'
      },
      {
        id: 'tv',
        name: '智能电视',
        description: '支持语音控制和场景联动的电视',
        icon: '/images/devices/tv.png',
        category: 'entertainment',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '在设置中选择网络设置，进入配对模式'
      },
      {
        id: 'camera',
        name: '智能摄像头',
        description: '支持移动侦测和云存储的摄像头',
        icon: '/images/devices/camera.png',
        category: 'security',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '重置设备并等待指示灯变为黄色闪烁'
      },
      {
        id: 'sensor',
        name: '门窗传感器',
        description: '检测门窗开关状态的传感器',
        icon: '/images/devices/sensor.png',
        category: 'security',
        hasModel: true,
        hasSerial: false,
        pairingInstruction: '撕掉绝缘片，设备自动进入配对模式'
      },
      {
        id: 'curtain',
        name: '智能窗帘',
        description: '定时开关和远程控制的窗帘',
        icon: '/images/devices/curtain.png',
        category: 'appliance',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '同时按住开和关按键10秒进入配对'
      },
      {
        id: 'thermostat',
        name: '温控器',
        description: '智能温度调节和节能控制',
        icon: '/images/devices/thermostat.png',
        category: 'climate',
        hasModel: true,
        hasSerial: true,
        pairingInstruction: '进入设置菜单选择添加新设备'
      }
    ]

    this.setData({ 
      deviceTypes,
      filteredDeviceTypes: deviceTypes // 初始化为所有设备类型
    })
  },
// 更新过滤后的设备类型
  updateFilteredDeviceTypes() {
    let types = this.data.deviceTypes
    
    // 分类过滤
    if (this.data.currentCategory !== 'all') {
      types = types.filter(type => type.category === this.data.currentCategory)
    }
    
    // 关键词搜索
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase()
      types = types.filter(type => 
        type.name.toLowerCase().includes(keyword) ||
        type.description.toLowerCase().includes(keyword)
      )
    }
    
    this.setData({ filteredDeviceTypes: types })
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword }, () => {
      this.updateFilteredDeviceTypes()
    })
  },

  // 清除搜索
  onClearSearch() {
    this.setData({ searchKeyword: '' }, () => {
      this.updateFilteredDeviceTypes()
    })
  },

  // 分类切换
  onCategoryChange(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ currentCategory: category }, () => {
      this.updateFilteredDeviceTypes()
    })
  },

  // 选择设备类型
  onSelectDeviceType(e) {
    const deviceType = e.currentTarget.dataset.type
    console.log('选择的设备类型:', deviceType)
    
    this.setData({
      selectedDeviceType: deviceType.id,
      selectedDeviceTypeObj: deviceType,
      deviceConfig: {
        ...this.data.deviceConfig,
        name: deviceType.name,
        icon: deviceType.icon
      }
    })
  },
  // 加载房间列表
  async loadRoomList() {
    try {
      const { roomAPI } = require('../../utils/api.js')
      const rooms = await roomAPI.getRoomList()
      
      // 如果有传递的房间ID，默认选中该房间
      let selectedRoomIndex = -1
      if (this.roomId) {
        selectedRoomIndex = rooms.findIndex(room => room.id === this.roomId)
      }
      
      this.setData({
        roomList: rooms,
        selectedRoomIndex: selectedRoomIndex,
        selectedRoom: selectedRoomIndex >= 0 ? rooms[selectedRoomIndex] : null
      })
    } catch (error) {
      console.error('加载房间列表失败:', error)
    }
  },

  // 计算属性：过滤后的设备类型
  get filteredDeviceTypes() {
    let types = this.data.deviceTypes
    
    // 分类过滤
    if (this.data.currentCategory !== 'all') {
      types = types.filter(type => type.category === this.data.currentCategory)
    }
    
    // 关键词搜索
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase()
      types = types.filter(type => 
        type.name.toLowerCase().includes(keyword) ||
        type.description.toLowerCase().includes(keyword)
      )
    }
    
    return types
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
  },

  // 清除搜索
  onClearSearch() {
    this.setData({ searchKeyword: '' })
  },

  // 分类切换
  onCategoryChange(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ currentCategory: category })
  },

  // 选择设备类型
 // 选择设备类型
onSelectDeviceType(e) {
  const deviceType = e.currentTarget.dataset.type
  console.log('选择的设备类型:', deviceType)
  
  this.setData({
    selectedDeviceType: deviceType.id,
    selectedDeviceTypeObj: deviceType,
    deviceConfig: {
      ...this.data.deviceConfig,
      name: deviceType.name,
      icon: deviceType.icon
    }
  }, () => {
    // 回调函数确保数据已更新
    console.log('更新后的selectedDeviceType:', this.data.selectedDeviceType)
  })
},

  // 下一步
  onNextStep() {
    const { currentStep } = this.data
    
    if (currentStep === 1 && !this.data.selectedDeviceType) {
      wx.showToast({
        title: '请选择设备类型',
        icon: 'none'
      })
      return
    }
    
    if (currentStep === 2 && (!this.data.deviceConfig.name || this.data.selectedRoomIndex < 0)) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    
    if (currentStep === 3) {
      this.startDeviceConnection()
      return
    }
    
    this.setData({ currentStep: currentStep + 1 })
    
    // 如果是第三步，开始扫描Wi-Fi
    if (currentStep === 2) {
      this.scanWifiNetworks()
    }
  },

  // 上一步
  onPrevStep() {
    if (this.data.currentStep > 1) {
      this.setData({ 
        currentStep: this.data.currentStep - 1,
        connectionStep: 1,
        isScanning: false,
        isConnecting: false
      })
    }
  },

  // 设备名称变化
  onDeviceNameChange(e) {
    const name = e.detail.value
    this.setData({
      deviceConfig: {
        ...this.data.deviceConfig,
        name: name
      }
    })
  },

  // 房间选择变化
  onRoomChange(e) {
    const index = e.detail.value
    const selectedRoom = this.data.roomList[index]
    this.setData({
      selectedRoomIndex: parseInt(index),
      selectedRoom: selectedRoom
    })
  },

  // 位置变化
  onPositionChange(e) {
    const position = e.detail.value
    this.setData({
      deviceConfig: {
        ...this.data.deviceConfig,
        position: position
      }
    })
  },

  // 型号变化
  onModelChange(e) {
    const model = e.detail.value
    this.setData({
      deviceConfig: {
        ...this.data.deviceConfig,
        model: model
      }
    })
  },

  // 序列号变化
  onSerialNumberChange(e) {
    const serialNumber = e.detail.value
    this.setData({
      deviceConfig: {
        ...this.data.deviceConfig,
        serialNumber: serialNumber
      }
    })
  },

  // 图标选择
  onIconSelect(e) {
    const icon = e.currentTarget.dataset.icon
    this.setData({
      deviceConfig: {
        ...this.data.deviceConfig,
        icon: icon
      }
    })
  },

  // 扫描Wi-Fi网络
  async scanWifiNetworks() {
    // 模拟Wi-Fi扫描
    this.setData({ isLoading: true, loadingText: '正在扫描Wi-Fi网络...' })
    
    setTimeout(() => {
      const availableWifi = [
        { ssid: 'Home-WiFi-5G', strength: '强', security: 'WPA2' },
        { ssid: 'Home-WiFi', strength: '强', security: 'WPA2' },
        { ssid: 'TP-LINK_2.4G', strength: '中', security: 'WPA2' },
        { ssid: 'Xiaomi_WiFi', strength: '弱', security: 'WPA2' },
        { ssid: 'Guest-WiFi', strength: '中', security: 'WPA' }
      ]
      
      this.setData({
        availableWifi,
        isLoading: false
      })
    }, 2000)
  },

  // 开始设备连接
  async startDeviceConnection() {
    if (this.data.connectionStep === 1) {
      // 第一步：设备通电
      this.setData({ connectionStep: 2 })
      return
    }
    
    if (this.data.connectionStep === 2) {
      // 第二步：开始扫描设备
      this.setData({ isScanning: true })
      
      // 模拟设备扫描
      setTimeout(() => {
        this.setData({
          connectionStep: 3,
          isScanning: false
        })
      }, 3000)
      return
    }
    
    if (this.data.connectionStep === 3 && this.data.selectedWifi && this.data.wifiPassword) {
      // 第三步：连接Wi-Fi
      this.setData({ isConnecting: true, loadingText: '正在连接设备...' })
      
      try {
        // 模拟设备连接过程
        await this.connectDeviceToNetwork()
        
        this.setData({
          connectionStep: 4,
          isConnecting: false,
          currentStep: 4
        })
        
        // 添加设备到系统
        await this.addDeviceToSystem()
        
      } catch (error) {
        console.error('设备连接失败:', error)
        this.setData({ isConnecting: false })
        wx.showToast({
          title: '连接失败，请重试',
          icon: 'error'
        })
      }
    }
  },

  // 连接设备到网络
  connectDeviceToNetwork() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟连接成功
        if (Math.random() > 0.2) { // 80%成功率
          resolve()
        } else {
          reject(new Error('连接超时'))
        }
      }, 4000)
    })
  },

  // 添加设备到系统
  async addDeviceToSystem() {
    const { deviceConfig, selectedDeviceType, selectedRoom } = this.data
    
    // 生成设备ID
    const deviceId = `${selectedDeviceType}-${Date.now()}`
    
    // 创建新设备对象
    const newDevice = {
      id: deviceId,
      name: deviceConfig.name,
      type: selectedDeviceType,
      room: selectedRoom.id,
      roomName: selectedRoom.name,
      icon: deviceConfig.icon,
      status: 'online',
      powerState: 'off',
      position: deviceConfig.position,
      model: deviceConfig.model,
      serialNumber: deviceConfig.serialNumber,
      isFavorite: false,
      lastUsed: null,
      firmware: 'v1.0.0',
      addTime: new Date().toISOString().split('T')[0]
    }
    
    // 根据设备类型添加特定属性
    switch(selectedDeviceType) {
      case 'smart-light':
        newDevice.brightness = 50
        newDevice.supportColor = true
        newDevice.color = 'natural'
        break
      case 'ac':
        newDevice.temperature = 24
        newDevice.mode = 'cool'
        newDevice.windSpeed = 'auto'
        break
      case 'tv':
        newDevice.channel = 1
        newDevice.volume = 50
        newDevice.source = 'hdmi1'
        break
    }
    
    // 添加到全局设备列表
    const app = getApp()
    app.globalData.deviceList.push(newDevice)
    
    // 保存到本地存储
    wx.setStorageSync('deviceList', app.globalData.deviceList)
    
    console.log('新设备添加成功:', newDevice)
  },

  // 选择Wi-Fi网络
  onSelectWifi(e) {
    const wifi = e.currentTarget.dataset.wifi
    this.setData({
      selectedWifi: wifi,
      wifiPassword: ''
    })
  },

  // Wi-Fi密码变化
  onWifiPasswordChange(e) {
    const password = e.detail.value
    this.setData({ wifiPassword: password })
  },

  // 切换手动输入
  toggleManualInput() {
    this.setData({ showManualInput: !this.data.showManualInput })
  },

  // 手动设备ID变化
  onManualDeviceIdChange(e) {
    const deviceId = e.detail.value
    this.setData({ manualDeviceId: deviceId })
  },

  // 手动连接
  onManualConnect() {
    if (!this.data.manualDeviceId) {
      wx.showToast({
        title: '请输入设备ID',
        icon: 'none'
      })
      return
    }
    
    this.setData({ isLoading: true, loadingText: '正在验证设备...' })
    
    // 模拟手动连接
    setTimeout(() => {
      this.setData({
        isLoading: false,
        connectionStep: 4,
        currentStep: 4
      })
      
      // 添加设备到系统
      this.addDeviceToSystem()
      
    }, 2000)
  },

  // 继续添加设备
  onAddAnother() {
    // 重置状态，保留房间选择
    this.setData({
      currentStep: 1,
      searchKeyword: '',
      currentCategory: 'all',
      selectedDeviceType: '',
      selectedDeviceTypeObj: null,
      deviceConfig: {
        name: '',
        position: '',
        model: '',
        serialNumber: '',
        icon: '/images/devices/light.png'
      },
      connectionStep: 1,
      isScanning: false,
      isConnecting: false,
      selectedWifi: null,
      wifiPassword: '',
      showManualInput: false,
      manualDeviceId: ''
    })
  },

  // 完成添加
  onComplete() {
    // 返回设备列表页面
    wx.navigateBack()
    
    // 显示成功消息
    wx.showToast({
      title: '设备添加成功',
      icon: 'success',
      duration: 2000
    })
  }
})